/*
 * @Description:
 * @Version: 2.0
 * @Autor: wangmiao
 * @Date: 2022-07-22 13:27:27
 * @LastEditors: wangmiao
 * @LastEditTime: 2022-08-31 11:17:23
 */
import axios, { AxiosRequestConfig } from "axios";
import NProgress from "nprogress";
import { ResType, Http } from "./types";
import { EVN_VARIABLE, PRO_VARIABLE } from "@/constants/env";
import { ElMessage } from "element-plus";
// 设置请求头和请求路径
console.log(import.meta.env);
axios.defaults.baseURL =
  import.meta.env.VITE_APP_ENV === EVN_VARIABLE ? "/api" : "/";
axios.defaults.timeout = 10000;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    // 请求拦截部分
    return config;
  },
  (error) => {
    return error;
  }
);
axios.interceptors.response.use((res) => {
  let result;
  // 请求响应部分
  if (res.status === 200) {
    result = res.data;
  } else {
    result = res;
    ElMessage.error("请求失败！！！");
  }

  return result;
});
const http: Http = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start();
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done();
          resolve(res);
        })
        .catch((err) => {
          NProgress.done();
          reject(err.data);
        });
    });
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start();
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done();
          resolve(res);
        })
        .catch((err) => {
          NProgress.done();
          reject(err.data);
        });
    });
  },
};

export default http;
